package com.doradance.app.home;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.util.StateSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.cncn.youmengsharelib.ShareListener;
import com.cncn.youmengsharelib.SharePlatform;
import com.cncn.youmengsharelib.ui.SharePlatformsFragment;
import com.doradance.R;
import com.doradance.account.UrlCenter;
import com.doradance.account.utils.CustomDialog;
import com.doradance.account.utils.MineJCVideo;
import com.doradance.account.utils.MyListView;
import com.doradance.account.utils.ShareUtil;
import com.doradance.account.utils.VipDialogUtil;
import com.doradance.account.utils.WifiUtils;
import com.doradance.common.http.MyHttpRequest;
import com.doradance.entity.CoursesDetailAdapter;
import com.doradance.entity.CoursesIdEntity;
import com.doradance.entity.IndexEntity;
import com.doradance.entity.RefreshHome;
import com.doradance.entity.ShareBackEntity;
import com.doradance.entity.UpdataDetailEntity;
import com.doradance.entity.UpdataMemberEntity;
import com.doradance.wxapi.WXEntryActivity;
import com.example.xlhratingbar_lib.XLHRatingBar;
import com.hpplay.callback.ExecuteResultCallBack;
import com.hpplay.callback.HpplayWindowPlayCallBack;
import com.hpplay.callback.TransportCallBack;
import com.hpplay.link.HpplayLinkControl;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.tencent.bugly.crashreport.inner.InnerApi;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import fm.jiecao.jcvideoplayer_lib.JCMediaManager;
import fm.jiecao.jcvideoplayer_lib.JCUtils;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerManager;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

public class CoursesDetailActivity extends AppCompatActivity implements TransportCallBack, ExecuteResultCallBack {
    @Bind(R.id.iv_video_back)
    ImageView mIvVideoBack;
    @Bind(R.id.tv_viodeo_title)
    TextView mTvViodeoTitle;
    @Bind(R.id.iv_isCollect)
    ImageView mIvIsCollect;
    @Bind(R.id.tv_isCollect)
    TextView mTvIsCollect;
    @Bind(R.id.ratingbarId_video)
    XLHRatingBar mRatingbarIdVideo;
    @Bind(R.id.tv_video_score)
    TextView mTvVideoScore;
    @Bind(R.id.tv_video_category)
    TextView mTvVideoCategory;
    @Bind(R.id.tv_video_age)
    TextView mTvVideoAge;
    @Bind(R.id.tv_video_num)
    TextView mTvVideoNum;
    @Bind(R.id.iv_member_grade)
    ImageView mIvMemberGrade;
    @Bind(R.id.tv_video_vip)
    TextView mTvVideoVip;
    @Bind(R.id.tv_course_introduct)
    TextView mTvCourseIntroduct;
    @Bind(R.id.civ_teacher_head)
    CircleImageView mCivTeacherHead;
    @Bind(R.id.tv_teacher_head)
    TextView mTvTeacherHead;
    @Bind(R.id.lv_add_course)
    MyListView mLvAddCourse;
    @Bind(R.id.rl_down)
    RelativeLayout mRlDown;
    @Bind(R.id.tv_teacher_trou)
    TextView mTvTeacherTrou;
    @Bind(R.id.tv_course_evaluate)
    TextView mTvCourseEvaluate;
    @Bind(R.id.ll_add_evaluate)
    LinearLayout mLlAddEvaluate;
    @Bind(R.id.tv_all_comments)
    TextView mTvAllComments;
    @Bind(R.id.sv_course)
    ScrollView mSvCourse;
    @Bind(R.id.btn_comments)
    Button mBtnComments;
    @Bind(R.id.ll_isCollect)
    LinearLayout mLlIsCollect;
    @Bind(R.id.videoplayer)
    MineJCVideo mVideoplayer;
    @Bind(R.id.rl_detail_teacher)
    RelativeLayout mRlDetailTeacher;
    @Bind(R.id.tv_start_evaluating)
    TextView mTvStartEvaluating;
    @Bind(R.id.rl_introduct_down)
    RelativeLayout mRlIntroductDown;
    @Bind(R.id.iv_video_cour_down)
    ImageView mIvVideoCourDown;
    @Bind(R.id.iv_introduct_down)
    ImageView mIvIntroductDown;
    private String id;
    @Bind(R.id.iv_video_share)
    ImageView mIvStartEvaluating;
    private List<CoursesIdEntity.ChaptersBean> chapters;
    ArrayList<List<CoursesIdEntity.CommentsBean>> lists = new ArrayList<>();
    private int user_limit;
    private int vip_limit;
    private Boolean isDown = true;
    private Boolean isTroDown = false;
    private Boolean isFavorite;
    private boolean isConnect;
    private int mWidth;
    private int mHeigh;
    private String front_url;
    private boolean isPlay;
    List<CoursesIdEntity.CommentsBean> comments;
    Dialog dialog;
    String back_url;
    private HpplayLinkControl mHpplayLinkControl;
    private boolean bAutoSendClickFlag = false;
    private long mPrevCastStopTimeStamp = 0;
    private static final String TAG = "CoursesActivity";
    private HpplayWindowPlayCallBack mHpplayWindowPlayCallBack = null;
    //弹起dialog
    private View myView;
    private Boolean isFront = true;
    private String mVideoPlayingUrl = null;
    private String imageUrl;
    private int last_duration;
    private int finalI;//初始化一个值
    private CoursesIdEntity o1;
    private CoursesDetailAdapter coursesDetailAdapter;
    /**
     * 官网申请到的Key
     */
    public static Activity CoursesDetailActivity;
    private static final String mKey = "4a2fdac3756f54a783c51b4748a1fe66";

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_courses_detail);
        ButterKnife.bind(this);
        CoursesDetailActivity = this;
        //得到当前界面的装饰视图
//        if(Build.VERSION.SDK_INT >= 21) {
//            View decorView = getWindow().getDecorView();
//            //设置让应用主题内容占据状态栏和导航栏
//            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
//            decorView.setSystemUiVisibility(option);
//            //设置状态栏和导航栏颜色为透明
//            getWindow().setStatusBarColor(Color.TRANSPARENT);
//            getWindow().setNavigationBarColor(Color.TRANSPARENT);
//        }
//        //隐藏标题栏
//        ActionBar actionBar = getSupportActionBar();
//        actionBar.hide();
        id = getIntent().getStringExtra("id");
        Log.e("courId",id);
        ShareUtil.setFinalId(-1);
        initData();
        initShareCharpter();
        EventBus.getDefault().register(this);
        mSvCourse.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                View childView = mSvCourse.getChildAt(0);
                if (childView != null && childView.getMeasuredHeight() <= mSvCourse.getScrollY() + mSvCourse.getHeight()) {
                    mBtnComments.setVisibility(View.VISIBLE);
                } else {
                    mBtnComments.setVisibility(View.GONE);
                }
            }
        });
        mHpplayLinkControl = HpplayLinkControl.getInstance();
        mHpplayLinkControl.setDebug(true);
        mHpplayLinkControl.initHpplayLink(this, mKey);
        mHpplayLinkControl.setTransportCallBack(this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if(ShareUtil.getShareChapterId()!=-1){
//            finish();
//            Intent intent = new Intent(CoursesDetailActivity.this,CoursesDetailActivity.class);
//            startActivity(intent);
//            initShareCharpter();
        }
    }

    //分享回调
    private void initShareCharpter() {
        if(ShareUtil.getShareChapterId()!=-1){
            Log.e("sfdsfdsfsdsdfsd11",ShareUtil.getShareChapterId()+"");
            String shareBackUrl = String.format(UrlCenter.SHARE_BACK,ShareUtil.getShareChapterId());
            MyHttpRequest request = new MyHttpRequest(this);
            UrlParams urlParams = new UrlParams();
            urlParams.put("id",ShareUtil.getShareChapterId()+"");
            request.post(shareBackUrl, urlParams, new DataRequestListener<String>(String.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }
                @Override
                public void onSuccess(String o) {
                    super.onSuccess(o);
                    ShareUtil.setShareChapterId(-1);
                    initData();
                }
                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(getApplicationContext(),strMsg);
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
        //退出整个通信并释放
        mHpplayLinkControl.castDisconnectDevice();
        JCVideoPlayer.releaseAllVideos();
    }
    /**
     * 不要忘了这两个方法
     */
    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UpdataDetailEntity refreshEvent) {
        initEvaluate(refreshEvent.comments.getComments());
        initData(refreshEvent.comments);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ShareBackEntity refreshEvent) {
        initShareCharpter();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UpdataMemberEntity refreshEvent) {
        initData();
    }

    private void initData() {
        MyHttpRequest request = new MyHttpRequest(this);
        final String coursesUrl = String.format(UrlCenter.COURSES_ID, id);
        request.get(coursesUrl, null, new DataRequestListener<CoursesIdEntity>(CoursesIdEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(final CoursesIdEntity o) {
                super.onSuccess(o);
                updataDetail(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                EasyToast.showToast(getApplicationContext(), strMsg);
            }
        });
    }

    private void updataDetail(final CoursesIdEntity o) {
        o1 = o;
        if (o.isFavorite() == true) {
            if (Util.isOnMainThread()) {
                Glide.with(CoursesDetailActivity.this).load(R.mipmap.icon_collection_light).into(mIvIsCollect);
            }
            mTvIsCollect.setText("已收藏");
            isFavorite = true;
        } else {
            if (Util.isOnMainThread()) {
                Glide.with(CoursesDetailActivity.this).load(R.mipmap.icon_collection_unlit).into(mIvIsCollect);
            }
            mTvIsCollect.setText("未收藏");
            isFavorite = false;
        }
        mTvVideoAge.setText(o.getAge_ranges().get(0).getName());
        vip_limit = o.getVip_limit();
        user_limit = o.getUser_vip().getId();
        ShareUtil.setShareCourseId(o.getId());
        mRatingbarIdVideo.setCountSelected(o.getGrade_int());
        mTvVideoScore.setText(o.getGrade_int() + "分");
        mTvViodeoTitle.setText(o.getName());
        mTvVideoCategory.setText(o.getCategory());
        mTvVideoNum.setText(o.getLearning_count() + "人学过");
        if (o.getUser_vip().isOpen() && o.getUser_vip().isHighest()) {
            mTvVideoVip.setText("");
            ShareUtil.setIsMember("true");
        } else if (o.getUser_vip().isOpen() && !o.getUser_vip().isHighest()) {
            mTvVideoVip.setText("升级会员");
            startVipActivity();
            ShareUtil.setIsMember("true");
        } else {
            mTvVideoVip.setText("成为会员");
            startVipActivity();
            ShareUtil.setIsMember("false");
        }
        ShareUtil.setDetailKey(o.getTicket());
        ShareUtil.setIsIsStudy(o.isLearnt());
        ShareUtil.setCourseId(CoursesDetailActivity.this.id);
        Glide.with(CoursesDetailActivity.this).load(o.getUser_vip().getIcon()).into(mIvMemberGrade);
        mTvCourseIntroduct.setText(o.getSummary());
        mTvCourseIntroduct.setLines(2);
        mTvCourseIntroduct.setEllipsize(TextUtils.TruncateAt.END);
        mRlIntroductDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isTroDown == false) {
                    mTvCourseIntroduct.setText(o.getSummary());
                    mTvCourseIntroduct.setMaxLines(100);
                    Glide.with(CoursesDetailActivity.this).load(R.mipmap.icon_video_cour_up).into(mIvIntroductDown);
                    isTroDown = true;
                } else {
                    mTvCourseIntroduct.setText(o.getSummary());
                    mTvCourseIntroduct.setLines(2);
                    mTvCourseIntroduct.setEllipsize(TextUtils.TruncateAt.END);
                    Glide.with(CoursesDetailActivity.this).load(R.mipmap.icon_video_down).into(mIvIntroductDown);
                    isTroDown = false;
                }
            }
        });
        chapters = o.getChapters();
        comments = o.getComments();
        initCourseView(chapters, comments);
        initEvaluate(comments);
        Glide.with(CoursesDetailActivity.this).load(o.getTeacher().getAvatar()).asBitmap().dontAnimate().placeholder(R.mipmap.init_logo).into(mCivTeacherHead);
        mTvTeacherHead.setText(o.getTeacher().getName());
        mTvTeacherTrou.setText(o.getTeacher().getSummary());
        mTvCourseEvaluate.setText("(" + o.getCmnt_count() + "条评论)");
        mRlDetailTeacher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CoursesIdEntity.TeacherBean teacher = o.getTeacher();
                initDialog(teacher);
            }
        });
        if (o.getCmnt_count() > 0) {
            mTvAllComments.setVisibility(View.VISIBLE);
            mTvAllComments.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AllCommensActivity.start(CoursesDetailActivity.this, CoursesDetailActivity.this.id, o.isLearnt());
                }
            });
        }
        mLlIsCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFavorite == true) {
                    isFavoriteFalse();
                } else {
                    isFavoriteTrue();
                }
            }
        });
        mVideoplayer.setUp("", JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "");
        Glide.with(CoursesDetailActivity.this).load(o.getCover()).dontAnimate().placeholder(R.mipmap.icon_video_head).centerCrop().into(mVideoplayer.thumbImageView);
        mVideoplayer.thumbImageView.setAlpha(0.7f);

        mBtnComments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ShareUtil.getIsMember().equals("false")) {
                    VipDialogUtil.DetailDialog(CoursesDetailActivity.this, getString(R.string.no_vip), getString(R.string.become_vip_dialog));
                } else if (ShareUtil.getIsStudy() == false) {
                    VipDialogUtil.LearnDialog(CoursesDetailActivity.this, getString(R.string.no_learn), getString(R.string.watch_immediate), 0);
                } else {
                    UpCommentsActivity.start(CoursesDetailActivity.this, CoursesDetailActivity.this.id);
                }
            }
        });
        mTvStartEvaluating.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EvaluatingActivity.start(CoursesDetailActivity.this, o.getWjx_url());
            }
        });
        mIvStartEvaluating.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareUtil.setShareChapterId(-1);
                shareStudent(o.getCategory(), "我和"+"【"+ShareUtil.getBabyName()+"】"+"在妞秀APP学习了"+"【"+o1.getName()+"】", o.getCover(), "http://h5.doradance.cn/#/courseDetail?id=" + CoursesDetailActivity.this.id);
            }
        });


    }

    private void initData(CoursesIdEntity o){
        updataDetail(o);
    }

    private void startVipActivity() {
        mTvVideoVip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VipRechargeActivity.start(CoursesDetailActivity.this, id);
            }
        });
    }

    private void isFavoriteTrue() {
        MyHttpRequest request = new MyHttpRequest(this);
        UrlParams urlParams = new UrlParams();
        urlParams.put("courseId", id);
        String favoriteUrl = String.format(UrlCenter.FAVORITE_CANCEL, id);
        request.post(favoriteUrl, urlParams, new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                mIvIsCollect.setImageResource(R.mipmap.icon_collection_light);
//                Glide.with(CoursesDetailActivity.this).load(R.mipmap.icon_collection_light).into(mIvIsCollect);
                mTvIsCollect.setText("已收藏");
                EasyToast.showToast(getApplicationContext(),"已收藏");
                isFavorite = true;
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                EasyToast.showToast(getApplicationContext(), strMsg);
            }
        });
    }

    private void isFavoriteFalse() {
        MyHttpRequest request = new MyHttpRequest(this);
        String favoriteUrl = String.format(UrlCenter.FAVORITE_CANCEL, id);
        request.delete(favoriteUrl, null, new DataRequestListener<String>(String.class) {

            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                mIvIsCollect.setImageResource(R.mipmap.icon_collection_unlit);
//                Glide.with(CoursesDetailActivity.this).load(R.mipmap.icon_collection_unlit).into(mIvIsCollect);
                mTvIsCollect.setText("未收藏");
                EasyToast.showToast(getApplicationContext(),"取消收藏");
                isFavorite = false;
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                EasyToast.showToast(getApplicationContext(), strMsg);
            }
        });
    }

    private void initDialog(CoursesIdEntity.TeacherBean teacher) {
        final Dialog dialog = new Dialog(CoursesDetailActivity.this, R.style.Transparent);
        dialog.setContentView(R.layout.dialog_teacher);
        dialog.setCanceledOnTouchOutside(true);
        CircleImageView civDialogHead = (CircleImageView) dialog.findViewById(R.id.civ_dialog_head);
        TextView tvDialogName = (TextView) dialog.findViewById(R.id.tv_dialog_name);
        TextView tvDialogTrouduct = (TextView) dialog.findViewById(R.id.tv_dialog_trouduct);
        TextView tvDialogDetailTrouduct = (TextView) dialog.findViewById(R.id.tv_dialog_detail_trouduct);
        Glide.with(CoursesDetailActivity.this).load(teacher.getAvatar()).asBitmap().dontAnimate().placeholder(R.mipmap.init_logo).into(civDialogHead);
        dialog.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
        tvDialogName.setText(teacher.getName());
        tvDialogTrouduct.setText(Html.fromHtml(teacher.getSummary()));
        tvDialogDetailTrouduct.setText(Html.fromHtml(teacher.getDetail()));
        Window w = dialog.getWindow();
        WindowManager.LayoutParams lp = w.getAttributes();
        lp.dimAmount = 0.4f;
        w.setAttributes(lp);
        w.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        lp.x = 0;
        lp.y = 100;
        dialog.onWindowAttributesChanged(lp);
        dialog.show();
    }

    //初始化课程目录
    private void initCourseView(final List<CoursesIdEntity.ChaptersBean> chapters, List<CoursesIdEntity.CommentsBean> comments) {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        coursesDetailAdapter = new CoursesDetailAdapter(supportFragmentManager, this, chapters, o1, vip_limit, user_limit,o1.getId());
        mLvAddCourse.setAdapter(coursesDetailAdapter);
        if (ShareUtil.getFinalId() != -1) {
            coursesDetailAdapter.setCurrentItem(ShareUtil.getFinalId());
            coursesDetailAdapter.setClick(true);
            coursesDetailAdapter.notifyDataSetChanged();
        }

        coursesDetailAdapter.setOnShareFreeClickListener(new CoursesDetailAdapter.OnShareFreeClickListener() {
            @Override
            public void onClick(String title, String content, String image, String url) {
                shareStudent(title,"我和"+"【"+ShareUtil.getBabyName()+"】"+"在妞秀APP学习了"+"【"+o1.getName()+"】",image,url);
            }
        });
        mLvAddCourse.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                changeChapter(position);
            }
        });

        mRlDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isDown == false) {
                    mLvAddCourse.setVisibility(View.VISIBLE);
                    Glide.with(CoursesDetailActivity.this).load(R.mipmap.icon_video_cour_up).into(mIvVideoCourDown);
                    isDown = true;
                } else {
                    mLvAddCourse.setVisibility(View.GONE);
                    Glide.with(CoursesDetailActivity.this).load(R.mipmap.icon_video_down).into(mIvVideoCourDown);
                    isDown = false;
                }
            }
        });

    }

    private void changeChapter(final int position) {
        ShareUtil.setIsAuthorize(chapters.get(position).isAuthorize());
        if (!ShareUtil.getIsAuthorize() && ShareUtil.getIsMember().equals("false")) {
            VipDialogUtil.DetailDialog(CoursesDetailActivity.this, getString(R.string.no_vip), getString(R.string.become_vip_dialog));
            return;
        } else if (!ShareUtil.getIsAuthorize() && ShareUtil.getIsMember().equals("true")) {
            VipDialogUtil.DetailDialog(CoursesDetailActivity.this, "您当前是"+o1.getUser_vip().getName()+"会员，请升级到"+o1.getVip_name()+"会员才能观看", getString(R.string.upgrad));
            return;
        }
        if (ShareUtil.getFinalId() == -1) {
            if (ShareUtil.getIs3G() == true) {
                if (WifiUtils.isWifi(CoursesDetailActivity.this)) {
                    ShareUtil.setFinalId(position);
                    ShareUtil.setChapterId(chapters.get(position).getId());
                    //第一次播放。如果提醒打开每次进来第一次都做个提醒
                    coursesDetailAdapter.setCurrentItem(position);
                    coursesDetailAdapter.setClick(true);
                    coursesDetailAdapter.notifyDataSetChanged();
                    ShareUtil.setIsAuthorize(chapters.get(position).isAuthorize());
                    setChaptersStart(chapters, position);
                } else {
                    //3G提醒被打开,现在是4g
                    is3GMessage(CoursesDetailActivity.this, getString(R.string.is_3g), getString(R.string.stop_video), getString(R.string.play_video), position);
                }
            } else {
                ShareUtil.setFinalId(position);
                ShareUtil.setChapterId(chapters.get(position).getId());
                coursesDetailAdapter.setCurrentItem(position);
                coursesDetailAdapter.setClick(true);
                coursesDetailAdapter.notifyDataSetChanged();
                ShareUtil.setIsAuthorize(chapters.get(position).isAuthorize());
                setChaptersStart(chapters, position);
            }
        } else if (ShareUtil.getFinalId() != position) {
            //切换章节
            ShareUtil.setPauseVideoTime();
            last_duration = mVideoplayer.getCurrentPositionWhenPlaying();
            MyHttpRequest request = new MyHttpRequest(CoursesDetailActivity.this);
            JSONObject job = new JSONObject();
            try {
                job.put("ticket", ShareUtil.getDetailKey());
                job.put("course_id", ShareUtil.getCourseId());
                job.put("chapter_id", ShareUtil.getChapterId() + "");
                job.put("begin", ShareUtil.getStartVideoTime());
                job.put("end", ShareUtil.getPauseVideoTime());
                job.put("percent", getPercent() + "");
                job.put("last_duration", last_duration / 1000 + "");
                Log.e("last_durationla", last_duration + "");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            request.post(UrlCenter.LEARN_RECORDS, job, new DataRequestListener<String>(String.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(String o) {
                    super.onSuccess(o);
                    chaptersSuccess(position);
                    ShareUtil.setFinalId(position);
                }
                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                }
            });
        }
    }

    private void is3GMessage(final Context mContext, String title, String comfirm, String cancel, final int position) {
        LayoutInflater factory = LayoutInflater.from(this);
        View inflate = factory.inflate(R.layout.no_member_dialog, null);
        TextView tvDialogTitle = (TextView) inflate.findViewById(R.id.tv_dialog_title);
        TextView tvBecomeVip = (TextView) inflate.findViewById(R.id.tv_become_vip);
        TextView tvNoVip = (TextView) inflate.findViewById(R.id.tv_no_cancel);
        tvDialogTitle.setText(title);
        tvBecomeVip.setText(comfirm);
        tvNoVip.setText(cancel);
        final AlertDialog isMemberDialog = new AlertDialog.Builder(mContext)
                .setView(inflate).create();
        inflate.findViewById(R.id.tv_no_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareUtil.setFinalId(position);
                ShareUtil.setChapterId(chapters.get(position).getId());
                //第一次播放。如果提醒打开每次进来第一次都做个提醒
                coursesDetailAdapter.setCurrentItem(position);
                coursesDetailAdapter.setClick(true);
                coursesDetailAdapter.notifyDataSetChanged();
                ShareUtil.setIsAuthorize(chapters.get(position).isAuthorize());
                setChaptersStart(chapters, position);
                isMemberDialog.cancel();
            }
        });
        inflate.findViewById(R.id.tv_become_vip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isMemberDialog.cancel();
            }
        });
        //设置点击Dialog外部任意区域关闭Dialog
        isMemberDialog.setCanceledOnTouchOutside(true);
        isMemberDialog.show();

    }

    //切换成功 在请求一次替换数据
    private void chaptersSuccess(final int position) {
        MyHttpRequest request = new MyHttpRequest(this);
        final String coursesUrl = String.format(UrlCenter.COURSES_ID, id);
        request.get(coursesUrl, null, new DataRequestListener<CoursesIdEntity>(CoursesIdEntity.class) {

            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(CoursesIdEntity o) {
                super.onSuccess(o);
                initCourseView(o.getChapters(), comments);
                setChaptersStart(o.getChapters(), position);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    @SuppressLint("NewApi")
    private void setChaptersStart(List<CoursesIdEntity.ChaptersBean> chapters, int finalI) {
        ShareUtil.setIsAuthorize(chapters.get(finalI).isAuthorize());
        ShareUtil.setChapterId(chapters.get(finalI).getId());
        imageUrl = chapters.get(finalI).getCover();
        front_url = chapters.get(finalI).getFront_m3u8();
        mVideoPlayingUrl = front_url;
        back_url = chapters.get(finalI).getBack_m3u8();
        mVideoplayer.setUp(chapters.get(finalI).getFront_m3u8(), JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, chapters.get(finalI).getLast_duration() * 1000);
        mVideoplayer.startVideo();
//        PlaybackParams playback Params =mVideoplayer.mediaPlayer.getPlaybackParams();
//        Log.e("mediaPlayer",playbackParams.toString());
//        mVideoplayer.mediaPlayer.setPlaybackParams(mVideoplayer.mediaPlayer.getPlaybackParams().setSpeed(2f));
        ShareUtil.setIsIsStudy(true);
        Glide.with(CoursesDetailActivity.this).load(chapters.get(finalI).getCover()).placeholder(R.mipmap.init_logo).into(mVideoplayer.thumbImageView);
        ShareUtil.setStartVideoTime();
    }

    //初始化评价
    private void initEvaluate(List<CoursesIdEntity.CommentsBean> comments) {
        lists.clear();
        mLlAddEvaluate.removeAllViews();
        for (int i = 0; i < comments.size(); i++) {
            //首先引入要添加的View
            lists.add(comments);
            View view = View.inflate(this, R.layout.add_comments, null);
            //找到里面需要动态改变的控件
            TextView tvCommentName = (TextView) view.findViewById(R.id.tv_comment_name);
            CircleImageView civComments = (CircleImageView) view.findViewById(R.id.civ_comments);
            XLHRatingBar ratingbarIdComments = (XLHRatingBar) view.findViewById(R.id.ratingbarId_comments);
            TextView tvCommentsData = (TextView) view.findViewById(R.id.tv_comments_data);
            TextView tvCommentsDetail = (TextView) view.findViewById(R.id.tv_comments_detail);
            if (!TextUtils.isEmpty(comments.get(i).getNick_name())) {
                tvCommentName.setText(comments.get(i).getNick_name());
            } else {
                tvCommentName.setText("妞秀用户");
            }
            if (!TextUtils.isEmpty(comments.get(i).getAvatar())) {
                Glide.with(CoursesDetailActivity.this).load(comments.get(i).getAvatar()).asBitmap().dontAnimate().placeholder(R.mipmap.init_logo).into(civComments);
            } else {
                Glide.with(CoursesDetailActivity.this).load(R.mipmap.init_logo).asBitmap().dontAnimate().placeholder(R.mipmap.init_logo).into(civComments);
            }
            ratingbarIdComments.setCountSelected(comments.get(i).getGrade());
            tvCommentsData.setText(comments.get(i).getCreate_time());
            tvCommentsDetail.setText(comments.get(i).getContent());
            mLlAddEvaluate.addView(view);
        }
    }


    public static void start(Activity activity, int id) {
        Intent intent = new Intent(activity, CoursesDetailActivity.class);
        intent.putExtra("id", id + "");
        activity.startActivity(intent);
    }

    public static void start1(Context activity, int id) {
        Intent intent = new Intent(activity, CoursesDetailActivity.class);
        intent.putExtra("id", id + "");
        activity.startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            back();
            ShareUtil.setShareChapterId(-1);
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @SuppressLint("NewApi")
    @OnClick({R.id.iv_video_back, R.id.iv_chage_camera, R.id.iv_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_video_back:
                //切换章节
                back();
                ShareUtil.setShareChapterId(-1);
                break;

            case R.id.iv_chage_camera:
                if (TextUtils.isEmpty(back_url)) {
                    EasyToast.showToast(getApplicationContext(), "暂无视频");
                    return;
                }
                int position = mVideoplayer.getCurrentPositionWhenPlaying();
                JCUtils.saveProgress(this, front_url, 20);
                JCUtils.getSavedProgress(this, front_url);
                Glide.with(CoursesDetailActivity.this).load(imageUrl).into(mVideoplayer.thumbImageView);
                if (isFront) {
                    mVideoplayer.setUp(back_url, JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, position);
                    isFront = false;
                    mVideoPlayingUrl = back_url;
                } else {
                    mVideoplayer.setUp(front_url, JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, position);
                    isFront = true;
                    mVideoPlayingUrl = front_url;
                }
                mVideoplayer.startVideo();
                break;
            case R.id.iv_tv:
//                Log.e("mediaPlayer",playbackParams.toString());
//                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
//                     Log.e("mVideoplayer","mVideoplayer1");
//                    JCMediaManager.instance().mediaPlayer.setPlaybackParams(new PlaybackParams().setSpeed(2.0f));
//                }
//                Log.e("mVideoplayer","mVideoplayer2");

//                leBo();
                break;
        }
    }

    private void shareStudent(String title, String content, String image, String url) {
        SharePlatformsFragment fragment = SharePlatformsFragment.newInstance(title, content, image, url);
        fragment.setShareListener(new ShareListener() {
            @Override
            public void onShareSuccess(Activity shareActivity, SharePlatform platform) {
//                Toast.makeText(CoursesDetailActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onShareFailed(Activity shareActivity, SharePlatform platform) {
//                Toast.makeText(CoursesDetailActivity.this, "分享失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onShareCancel(Activity shareActivity, SharePlatform platform) {
//                Toast.makeText(CoursesDetailActivity.this, "取消分享", Toast.LENGTH_SHORT).show();
            }
        });
        fragment.show(getSupportFragmentManager(), "");
    }

    private void back() {
        if (TextUtils.isEmpty(ShareUtil.getStartVideoTime() + "")) {
            finish();
            return;
        }
        ShareUtil.setPauseVideoTime();
        last_duration = mVideoplayer.getCurrentPositionWhenPlaying();
        MyHttpRequest request = new MyHttpRequest(CoursesDetailActivity.this);
        JSONObject job = new JSONObject();
        try {
            job.put("ticket", ShareUtil.getDetailKey());
            job.put("course_id", ShareUtil.getCourseId());
            job.put("chapter_id", ShareUtil.getChapterId() + "");
            job.put("begin", ShareUtil.getStartVideoTime());
            job.put("end", ShareUtil.getPauseVideoTime());
            job.put("percent", getPercent() + "");
            job.put("last_duration", last_duration / 1000 + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request.post(UrlCenter.LEARN_RECORDS, job, new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                refreshHome();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                finish();
            }
        });
    }

    private void refreshHome() {
        MyHttpRequest request = new MyHttpRequest(this);
        UrlParams urlParams = new UrlParams();
        request.get(UrlCenter.INDEX, urlParams, new DataRequestListener<IndexEntity>(IndexEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(IndexEntity o) {
                super.onSuccess(o);
                EventBus.getDefault().post(new RefreshHome(o));
                finish();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    private void leBo() {
        bAutoSendClickFlag = false;
        if ((0 != mPrevCastStopTimeStamp) && (System.currentTimeMillis() - mPrevCastStopTimeStamp) < 3000) {
            Toast.makeText(CoursesDetailActivity.this, "投屏点击太频繁,请稍后重试", Toast.LENGTH_SHORT).show();
            return;
        }
        mPrevCastStopTimeStamp = System.currentTimeMillis();

        if (mVideoPlayingUrl == null || TextUtils.isEmpty(mVideoPlayingUrl)) {
            EasyToast.showToast(getApplicationContext(), "没有投影的视频");
            return;
        }
        Log.d(TAG, "show current playing url:" + mVideoPlayingUrl);
        //0:表示从头开始;
        if (null == mHpplayWindowPlayCallBack) {
            mHpplayWindowPlayCallBack = new HpplayWindowPlayCallBack() {
                @Override
                public void onHpplayWindowDismiss() {
                    //退出SDK界面
                    Log.d(TAG, "video play finished!!");
                    mHpplayWindowPlayCallBack = null;
                }

                @Override
                public void onIsConnect(boolean b) {
                    Log.d(TAG, "是否成功连接到电视 " + b);
                }

                @Override
                public void onIsPlaySuccess(boolean b) {
                    Log.d(TAG, "是否成功推送地址到电视 " + b);
                }
            };
            mHpplayLinkControl.showHpplayWindow(CoursesDetailActivity.this, mVideoPlayingUrl, 30, mHpplayWindowPlayCallBack, HpplayLinkControl.PUSH_VIDEO);
        } else {
            Log.d(TAG, "push video activity already request to started,then just ignore it!!");
        }

    }

    @Override
    public void onResultDate(Object arg0, int arg1) {
        switch (arg1) {
            case 1:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 2:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 3:
                isConnect = (Boolean) arg0;
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 4:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 5:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 6:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 7:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 8:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 9:
                //isBack = isBack ? false : true;
                //showCurseDialog(isBack?"当前为后台成功":"当前为前台播放");
                break;
            case 10:
                isPlay = (Boolean) arg0;
                showCurseDialog(isPlay ? "播放成功" : "播放失败");
                break;
            case 11:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 12:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 13:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 14:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 15:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 16:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 17:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 18:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 19:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 20:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 21:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            case 22:
                showCurseDialog((Boolean) arg0 ? "成功" : "失败");
                break;
            default:
                break;
        }
    }

    private void showCurseDialog(String msg) {

        try {
            int dialogW = 0;
            int dialogH = 0;
            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                dialogW = mWidth - 210;
                dialogH = mHeigh - 800;
            } else {
                dialogW = mWidth - 800;
                dialogH = mHeigh - 800;
            }
            View view = View.inflate(this, R.layout.hpplay_dialog_full_layout, null);
            TextView textView = (TextView) view.findViewById(R.id.text_log);

            textView.setText(msg);
            final CustomDialog dialog = new CustomDialog.Builder(this)
                    .setDiglogMatrix(dialogW, dialogH)
                    .setContentView(view)
                    .create();
            dialog.show();

            View installLayout = view.findViewById(com.happly.link.R.id.hpplay_install_layuot);
            TextView dialogTx = (TextView) view.findViewById(com.happly.link.R.id.hpplay_dialog_bt_tx);
            installLayout.setVisibility(View.VISIBLE);
            installLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });

            dialogTx.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTransportData(Object o) {
    }


    private Integer getPercent() {
        int position = mVideoplayer.getCurrentPositionWhenPlaying();
        int duration = mVideoplayer.getDuration();
        int progress = position * 100 / (duration == 0 ? 1 : duration);
        return progress;
    }
}
